package cn.com.qingz.modules.security.realm;

import java.util.List;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import cn.com.qingz.core.constantes.SystemConstantes;
import cn.com.qingz.core.exception.DicmfException;
import cn.com.qingz.modules.user.mapper.OrganizationMapper;
import cn.com.qingz.modules.user.model.User;
import cn.com.qingz.modules.user.service.UserService;

public class AuthorRealm extends AuthorizingRealm {

    private static Logger logger = Logger.getLogger(AuthorizingRealm.class);

    private String defaultRoles = ""; // 默认角色

    private String defaultPurviews = ""; // 默认权限

    @Autowired
    private UserService userService;

    @Autowired
    private OrganizationMapper orgMapper;

    /**
     * 重写认证方法
     */
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

        User currentUser = new User();
        currentUser.setUsername(token.getUsername());
        currentUser.setPassword(new Sha512Hash(token.getPassword()).toBase64());

        User user = userService.login(currentUser);

        if (token != null && user != null) {

            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();

            session.setAttribute("user", user);
            //			Organization org = orgMapper.getOrgById(user.getOrgId());
            //			session.setAttribute("org", org);

            return new SimpleAuthenticationInfo(user.getUsername(), token.getCredentials(), getName());
        } else {
            throw new DicmfException(SystemConstantes.LOGIN_TYPE, SystemConstantes.LOGIN_STYPE_MSG);
        }
    }

    /**
     * 重写授权方法
     */
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 测试时使用
        //		if (StringUtils.isNotEmpty(defaultRoles)) {// 角色授权
        //			String[] roles = defaultRoles.split(",");
        //			for (String role : roles)
        //				info.addRole(role);
        //		}

        User user = new User();
        user.setUsername(principals.getPrimaryPrincipal().toString());

        List<String> roles = userService.getRoleByLoginCode(user.getUsername());
        info.addRoles(roles);
        logger.info("角色：" + info.getRoles());

        for (String role : roles) {
            info.addStringPermissions(userService.getPermissionByRole(role));
        }

        logger.info("角色权限：" + info.getStringPermissions());
        return info;
    }

    /**
     * 更新用户授权信息缓存.
     */
    /*
     * protected void clearCachedAuthorizationInfo(PrincipalCollection
     * principal) { SimplePrincipalCollection principals = new
     * SimplePrincipalCollection( principal, getName());
     * clearCachedAuthorizationInfo(principals); }
     */

    /**
     * 清除所有用户授权信息缓存.
     */
    /*
     * public void clearAllCachedAuthorizationInfo() { Cache<Object,
     * AuthorizationInfo> cache = getAuthorizationCache(); if (cache != null) {
     * for (Object key : cache.keys()) { cache.remove(key); } } }
     */

    public String getDefaultRoles() {
        return defaultRoles;
    }

    public String getDefaultPurviews() {
        return defaultPurviews;
    }

    public void setDefaultRoles(String defaultRoles) {
        this.defaultRoles = defaultRoles;
    }

    public void setDefaultPurviews(String defaultPurviews) {
        this.defaultPurviews = defaultPurviews;
    }

    public static void main(String[] args) {
        System.out.println(new Sha512Hash("123456").toBase64());

    }
}
